#include "lvgl/lvgl.h"
#include <qrencode.h>
#include <stdio.h>
#include <stdlib.h>//malloc

/**
 * 创建一个二维码组件
 * @param parent 父视图
 * @param text 二维码内容
 * @return LVGL canvas 对象
 */
lv_obj_t *create_qrcode(lv_obj_t *parent, const char *text) {
    // 生成二维码数据
    QRcode *qrcode = QRcode_encodeString8bit(text, 0, QR_ECLEVEL_Q);
    if (!qrcode) {
        printf("QRcode generation failed!\n");
        return NULL;
    }

    int qr_size = qrcode->width;
    int scale = 4;  // 放大倍数
    int img_size = qr_size * scale;

    // 创建 LVGL canvas 对象
    lv_obj_t *canvas = lv_canvas_create(parent);

    // lv_canvas_set_buffer(canvas, malloc(LV_IMG_BUF_SIZE_TRUE_COLOR(img_size, img_size)),
    //                      img_size, img_size, LV_COLOR_FORMAT_RGB565);
    //上面代码报错：❌error: call to undeclared function 'LV_IMG_BUF_SIZE_TRUE_COLOR'; ISO C99 and later do not support implicit function declarations [-Wimplicit-function-declaration]
    //26 |     lv_canvas_set_buffer(canvas, malloc(LV_IMG_BUF_SIZE_TRUE_COLOR(img_size, img_size)),
    // ✅解决办法：在 LVGL v9+ 中，LV_IMG_BUF_SIZE_TRUE_COLOR() 已被弃用，改用 lv_color_t 类型计算：
    uint32_t buf_size = img_size * img_size * sizeof(lv_color_t);
    void *buf = malloc(buf_size);
    lv_canvas_set_buffer(canvas, buf, img_size, img_size, LV_COLOR_FORMAT_RGB565);

    // 填充白底
    lv_canvas_fill_bg(canvas, lv_color_white(), LV_OPA_COVER);

    // 绘制二维码黑白方块
    for (int y = 0; y < qr_size; y++) {
        for (int x = 0; x < qr_size; x++) {
            uint8_t b = qrcode->data[y * qr_size + x];
            lv_color_t color = (b & 1) ? lv_color_black() : lv_color_white();

            for (int dy = 0; dy < scale; dy++) {
                for (int dx = 0; dx < scale; dx++) {
                    lv_canvas_set_px(canvas, x * scale + dx, y * scale + dy, color, LV_OPA_100);
                }
            }
        }
    }

    QRcode_free(qrcode);
    printf("✅ QR code rendered on LVGL canvas\n");
    return canvas;
}
